package rmi;


import java.rmi.registry.Registry;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import replication.RegServer_Replication;

import messagepasser.LoginDAOSQL;


public class HeartBeat extends TimerTask{
	
	Map <Integer, Client> onlineUsers;
	Timer t;
	String serverType;
	RegServer_Replication repl;
	
	public HeartBeat (Map <Integer, Client> onlineUsers, Timer t, String serverType, RegServer_Replication r) {
		this.onlineUsers = onlineUsers;
		this.t = t;
		this.serverType = serverType;
		this.repl = r;
	}


	@Override
	public void run() {
		
		System.out.println("heartbeat");
				
		synchronized (this.onlineUsers) {
			
			Iterator<Integer> r_main = onlineUsers.keySet().iterator();
			
			while(r_main.hasNext()) {
				int id = r_main.next();
				try {
					System.out.println (id);
					onlineUsers.get(id).getUserId();
				}
				catch (Exception e) {
					System.out.println ("user may be offline");
					LoginDAOSQL logindao = new LoginDAOSQL("com.mysql.jdbc.Driver","jdbc:mysql:///tecbox","userprofile");
					logindao.removeIpPort(id);
					r_main.remove();
					Iterator<Integer> r_in = onlineUsers.keySet().iterator();
					while(r_in.hasNext()) {
						int userId = r_in.next();
						try {
							onlineUsers.get(userId).userOffline(id);
						}
						catch (Exception e1) {
							System.out.println ("user may be offline");
						}
					}
				}
			}
		}
		try {
			Registry registry = repl.getRegistryPrimaryIp();
			Server s = (Server) registry.lookup("TecBox_" + serverType + "Server");
			s.syncClients(onlineUsers);
		} catch (Exception e1) {
			Registry registry = repl.getRegistrySecondaryIp();
			try {
				Server s = (Server) registry.lookup("TecBox_" + serverType + "Server");
				s.syncClients(onlineUsers);
			} catch (Exception e) {}
		}
		
	}

}
